package com.atguigu.lease.web.admin.schedule;

import com.atguigu.lease.model.entity.LeaseAgreement;
import com.atguigu.lease.model.enums.LeaseStatus;
import com.atguigu.lease.web.admin.service.LeaseAgreementService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

/**
 * Author ChenYongSheng
 * Date 2025/10/13 16:58
 */
@Component
public class ScheduledTasks {

    @Autowired
    LeaseAgreementService leaseAgreementService;
    // 星期一凌晨2点刷新
//    @Scheduled(cron = "0 0 2 * * MON")
    // 每天凌晨2点刷新
    @Scheduled(cron = "0 0 2 * * ?")
//@Scheduled(cron = "1 * * * * ?")
    public void checkLeaseStatus(){

        //第一种写法
//        LambdaQueryWrapper<LeaseAgreement> lambdaQueryWrapper =new LambdaQueryWrapper<>();
//        lambdaQueryWrapper.in(LeaseAgreement::getStatus, LeaseStatus.SIGNED,LeaseStatus.WITHDRAWN);
//
//        List<LeaseAgreement> list = leaseAgreementService.list(lambdaQueryWrapper);
//        for (LeaseAgreement leaseAgreement : list) {
//            Date leaseEndDate = leaseAgreement.getLeaseEndDate();
//            Date now =new Date();
//            if (leaseEndDate.before(now)){
//                leaseAgreement.setStatus(LeaseStatus.EXPIRED);
//                leaseAgreementService.updateById(leaseAgreement);
//            }
//        }

        //第二种写法【推荐】
        Date date = new Date();

        LambdaUpdateWrapper<LeaseAgreement> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.in(LeaseAgreement::getStatus, LeaseStatus.SIGNED,LeaseStatus.WITHDRAWN)
                .le(LeaseAgreement::getLeaseEndDate,date)
                .set(LeaseAgreement::getStatus,LeaseStatus.EXPIRED);

        leaseAgreementService.update(lambdaUpdateWrapper);

    }

}
